import { BadRequestException, HttpException, HttpStatus, Injectable } from '@nestjs/common'
import { PrismaService } from '../prisma/prisma.service'
import RegisterDto from './dto/register.dto'
import { JwtService } from '@nestjs/jwt'
import LoginDto from './dto/login.dto'
import { CaptchaService } from '@/captcha/captcha.service'
import { UpdateAuthDto } from '@/auth/dto/update-auth-dto'
@Injectable()
export class AuthService {
    constructor(private prisma: PrismaService, private jwt: JwtService, private captcha: CaptchaService) {}
    async register(dto: RegisterDto) {
        const user = await this.prisma.user.create({
            data: {
                name: dto.name,
                password: dto.password,
            },
        })

        return this.token(user)
    }
    userInfo(id) {
        return this.prisma.user.findUnique({
            where: {
                id,
            },
        })
    }
    async update(id: number, UpdateAuthDto: UpdateAuthDto) {
        return this.prisma.user.update({
            where: {
                id,
            },
            data: UpdateAuthDto,
        })
    }
    async login(dto: LoginDto) {
        const user = await this.prisma.user.findUnique({
            where: {
                name: dto.name,
            },
        })
        if (!user) {
            const user = await this.prisma.user.create({
                data: {
                    name: dto.name,
                    password: dto.password,
                },
            })
            return this.token(user)
        }
        if (user.password != dto.password) {
            throw new HttpException(
                {
                    code: HttpStatus.BAD_REQUEST,
                    message: '密码或密码错误',
                    error: 'bad request',
                },
                HttpStatus.OK,
            )
        }
        return this.token(user)
    }
    async token({ id, name }) {
        console.log(id, name)
        return {
            token: await this.jwt.signAsync({
                name,
                sub: id,
            }),
        }
    }
}
